package nio.security;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Config
 * 
 * @author nio
 */
public class Config extends Object {
	private static final Logger log = LoggerFactory.getLogger(Config.class);
	private static final Config INSTANCE = new Config();
	private Properties properties = new Properties();

	/**
	 * Create a new instance of the Config.
	 */
	private Config() {
		super();
	}

	/**
	 * Initialize the configuration.
	 * 
	 * @throws Exception
	 *             if the initialization of the configuration fails.
	 */
	public static void initialize() throws Exception {
		Reader reader = null;
		try {
			reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constant.CONFIGURATION_FILE_NAME), Constant.CONFIGURATION_FILE_CHARSET);
			Config.INSTANCE.properties.load(reader);
		} catch (Exception e) {
			log.error("Failed to load the configuration. The configuration file '{}' have to be set to the classpath.", Constant.CONFIGURATION_FILE_NAME, e);
			throw new Exception(e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				log.error(e.getMessage(), e);
				throw new Exception(e);
			}
		}
	}

	/**
	 * Searches for the property with the specified key from configuration
	 * property list. If the key is not found in this property list, the default
	 * property list, and its defaults, recursively, are then checked. The
	 * method returns empty string if the property is not found.
	 * 
	 * @param key
	 *            the property key.
	 * @return the value in this property list with the specified key value.
	 */
	public static String getProperty(String key) {
		return Config.INSTANCE.properties.getProperty(key, "");
	}

}
